package utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.handler.CellWriteHandler;
import javafx.scene.control.Alert;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import model.*;
import model.excel.LogisticsRequirementExcel;
import model.vo.QueryRequirementVO;
import org.apache.poi.ss.usermodel.*;
import model.excel.LogisticsExcel;
import service.AttributeService;
import service.CustomerService;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelExportUtil {



    public static void exportRequirement(List<QueryRequirementVO> requirements) {
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存Excel文件");
            fileChooser.getExtensionFilters().add(
                    new FileChooser.ExtensionFilter("Excel文件", "*.xlsx")
            );

            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            // 格式化日期
            String formattedDate = currentDate.format(formatter);
            String fileName = "物流配送需求表" + formattedDate + ".xlsx";
            fileChooser.setInitialFileName(fileName);

            File file = fileChooser.showSaveDialog(new Stage());

            if (file != null) {
                ExcelExportUtil.exportLogisticsRequirement(requirements, file.getAbsolutePath());
                CommonUtil.showAlert("导出成功", "Excel文件已成功导出！", Alert.AlertType.INFORMATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
            CommonUtil.showAlert("导出失败", "导出Excel文件时发生错误：" + e.getMessage(), Alert.AlertType.ERROR);
        }
    }


    public static void exportLogisticsRequirement(List<QueryRequirementVO> requirementList, String filePath) {
        ExcelWriter excelWriter = null;
        try {
            // 创建ExcelWriter对象，设置从第0行开始写入数据
            excelWriter = EasyExcel.write(filePath, LogisticsRequirementExcel.class)
                    .registerWriteHandler(new CellWriteHandler() {
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            Row row = context.getRow();
                            if (row.getRowNum() == 0 && context.getColumnIndex() >= 0 && context.getColumnIndex() <= 5) {
                                row.setHeightInPoints(25);
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                writeCellStyle.setFillForegroundColor(IndexedColors.SEA_GREEN.getIndex());
                                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                WriteFont headFont = new WriteFont();
                                headFont.setBold(true);
                                headFont.setFontName("宋体");
                                headFont.setFontHeightInPoints((short) 14);
                                writeCellStyle.setWriteFont(headFont);
                            }
                        }
                    })
                    .registerWriteHandler(new CellWriteHandler() {
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            Row row = context.getRow();
                            if (row.getRowNum() == 1 && context.getColumnIndex() >= 0 && context.getColumnIndex() <= 5) {
                                row.setHeightInPoints(20);
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                writeCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                WriteFont headFont = new WriteFont();
                                headFont.setBold(true);
                                headFont.setFontName("宋体");
                                headFont.setFontHeightInPoints((short) 13);
                                writeCellStyle.setWriteFont(headFont);
                            }
                        }
                    })
                    .relativeHeadRowIndex(0)
                    .build();
            // 写入数据
            List<LogisticsRequirementExcel> dataList = new ArrayList<>();
            // 对每个客户创建一个工作表
            for (int i = 0; i < requirementList.size(); i++) {
                QueryRequirementVO requirement = requirementList.get(i);
                LogisticsRequirementExcel data = new LogisticsRequirementExcel();
                data.setSerial_no(requirement.getSerial_no_str());
                data.setItem(requirement.getItem());
                data.setRequirement(requirement.getRequirement());
                data.setProEffi(requirement.getProEffi());
                data.setSupervisor(requirement.getSupervisor());
                data.setResponsiblePerson(requirement.getResponsiblePerson());
                dataList.add(data);
            }
            // 创建新的写入sheet对象
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "物流运输要求").build();
            excelWriter.write(dataList, writeSheet);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }


    public static void exportLogistics(List<LogisticsInfo> logisticsInfoList, String filePath) {
        ExcelWriter excelWriter = null;
        try {
            // 设置样式
            WriteCellStyle headStyle = new WriteCellStyle();
            headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headStyle.setBorderBottom(BorderStyle.THIN);
            headStyle.setBorderLeft(BorderStyle.THIN);
            headStyle.setBorderRight(BorderStyle.THIN);
            headStyle.setBorderTop(BorderStyle.THIN);
            WriteFont headFont = new WriteFont();
            headFont.setBold(true);


            WriteCellStyle contentStyle = new WriteCellStyle();
            contentStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            contentStyle.setBorderBottom(BorderStyle.THIN);
            contentStyle.setBorderLeft(BorderStyle.THIN);
            contentStyle.setBorderRight(BorderStyle.THIN);
            contentStyle.setBorderTop(BorderStyle.THIN);

            // 创建ExcelWriter对象，设置从第3行开始写入数据
            excelWriter = EasyExcel.write(filePath, LogisticsExcel.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, contentStyle))
                    .registerWriteHandler(new CellWriteHandler() {
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            Row row = context.getRow();
                            if (row.getRowNum() == 0 && context.getColumnIndex() >= 0 && context.getColumnIndex() <= 3) {
                                row.setHeightInPoints(30);
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                WriteFont headFont = new WriteFont();
                                headFont.setBold(true);
                                headFont.setFontName("宋体");
                                headFont.setFontHeightInPoints((short) 14);
                                writeCellStyle.setWriteFont(headFont);
                            }
                        }
                    })
                    .registerWriteHandler(new CellWriteHandler() {
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            Row row = context.getRow();
                            if (row.getRowNum() == 1 && context.getColumnIndex() >= 0 && context.getColumnIndex() <= 3) {
                                row.setHeightInPoints(25);
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                writeCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                WriteFont sHeadFont = new WriteFont();
                                sHeadFont.setFontName("宋体");
                                sHeadFont.setFontHeightInPoints((short) 12);
                                writeCellStyle.setWriteFont(sHeadFont);
                            }
                        }
                    })
                    // 添加标红处理的CellWriteHandler
                    .registerWriteHandler(new CellWriteHandler() {
                        @Override
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            // 跳过表头行
                            if (context.getRow().getRowNum() < 2) {
                                return;
                            }

                            // 只处理内容列（第3列，索引为2）
                            if (context.getColumnIndex() >= 0 && context.getColumnIndex() <= 3) {
                                // 获取单元格内容
                                WriteCellData<?> cellData = context.getFirstCellData();

                                // 检查单元格内容是否需要标红
                                String sheetName = context.getWriteSheetHolder().getSheetName();
                                // 通过行索引获取对应的LogisticsExcel对象
                                if (cellData != null) {
                                    // 获取单元格样式
                                    WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();

                                    // 获取当前Sheet对应的数据列表
                                    if (sheetName != null) {
                                        // 从当前行所在的Sheet名称中提取客户ID
                                        int customerId = -1;
                                        try {
                                            // 尝试从sheetName中提取客户ID
                                            if (sheetName.startsWith("客户")) {
                                                String[] parts = sheetName.split("_");
                                                if (parts.length > 0) {
                                                    String customerIdStr = parts[0].substring(2);
                                                    customerId = Integer.parseInt(customerIdStr);
                                                }
                                            }
                                        } catch (Exception e) {
                                            // 提取失败，忽略
                                        }

                                        // 如果能够获取到客户ID，则查询对应的标红信息
                                        if (customerId > 0) {
                                            CustomerService customerService = new CustomerService();
                                            Customer customer = customerService.getCustomerById(customerId);
                                            if (customer != null) {
                                                // 获取当前单元格的项目名称（第2列）
                                                String displayName = null;
                                                if (context.getColumnIndex() == 1) {
                                                    // 如果是项目列，直接获取
                                                    displayName = cellData.getStringValue();
                                                } else {
                                                    // 如果是其他列，获取同行的项目列
                                                    WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
                                                    Sheet sheet = writeSheetHolder.getSheet();
                                                    Row currentRow = sheet.getRow(context.getRowIndex());
                                                    Cell itemCell = currentRow.getCell(1); // 获取第2列（索引为1）
                                                    if (itemCell != null) {
                                                        displayName = itemCell.getStringCellValue();
                                                    }
                                                }

                                                if (displayName != null) {
                                                    // 获取属性定义
                                                    AttributeDefinition attr = AttributeService.getAttributeByDisplayName(displayName);
                                                    if (attr != null) {
                                                        // 检查是否需要标红
                                                        if (customer.isAttributeHighlighted(attr.getAttributeId())) {
                                                            WriteFont font = new WriteFont();
                                                            font.setColor(IndexedColors.RED.getIndex());
                                                            writeCellStyle.setWriteFont(font);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    })
                    .relativeHeadRowIndex(0)
                    .build();

            //如果是模板
            if (logisticsInfoList.size() == 0) {
                List<LogisticsExcel> dataList = generateExcelTemplate();
                WriteSheet writeSheet = EasyExcel.writerSheet(0, "模板").build();
                // 写入数据
                excelWriter.write(dataList, writeSheet);
            }else{
                // 对每个客户创建一个工作表
                for (int i = 0; i < logisticsInfoList.size(); i++) {
                    LogisticsInfo info = logisticsInfoList.get(i);
                    String sheetName = "客户" + (i + 1) + "_" + info.getName();

                    // 获取该客户的标红信息
                    LogisticsHighlight highlight = DBUtil.getLogisticsHighlightByLogisticsId(info.getId());

                    // 生成数据
                    List<LogisticsExcel> dataList = generateExcelData(info, highlight);

                    // 创建新的写入sheet对象
                    WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetName).build();

                    // 写入数据
                    excelWriter.write(dataList, writeSheet);
                }
            }

        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    private static List<LogisticsExcel> generateExcelData(LogisticsInfo info, LogisticsHighlight highlight) {
        List<LogisticsExcel> dataList = new ArrayList<>();

        // 添加所有行数据，并根据标红信息设置是否标红
        addExcelRow(dataList, "1", "客户名称", info.getName(), highlight.getNameHighlight() == 1);
        addExcelRow(dataList, "2", "仓库地址", info.getAddress(), highlight.getAddressHighlight() == 1);
        addExcelRow(dataList, "3", "里程（KM）", info.getKm() + "KM", highlight.getKmHighlight() == 1);
        addExcelRow(dataList, "4", "客户联系人", info.getContacts(), highlight.getContactsHighlight() == 1);
        addExcelRow(dataList, "5", "到达时间要求", info.getTimeInput(), highlight.getTimeInputHighlight() == 1);
        addExcelRow(dataList, "6", "是否需要到达首战", info.getIsFirstBattleArrival(), highlight.getIsFirstBattleArrivalHighlight() == 1);
        addExcelRow(dataList, "7", "车厢温度要求（°C）", info.getTruckTempMin() + "-" + info.getTruckTempMax() + "°C",
                highlight.getTruckTempMinHighlight() == 1 || highlight.getTruckTempMaxHighlight() == 1);
        addExcelRow(dataList, "8", "产品温度要求（°C）", info.getProductTempMin() + "-" + info.getProductTempMax() + "°C",
                highlight.getProductTempMinHighlight() == 1 || highlight.getProductTempMaxHighlight() == 1);
        addExcelRow(dataList, "9", "测温方式", info.getMeasureMethod(), highlight.getMeasureMethodHighlight() == 1);
        addExcelRow(dataList, "10", "温控设备要求品牌/类型", info.getEquipmentType(), highlight.getEquipmentTypeHighlight() == 1);
        addExcelRow(dataList, "11", "温控设备数量", info.getEquipmentNum(), highlight.getEquipmentNumHighlight() == 1);
        addExcelRow(dataList, "12", "是否开箱测温", info.getOpenBox(), highlight.getOpenBoxHighlight() == 1);
        addExcelRow(dataList, "13", "是否带托运输", info.getTrayTransport(), highlight.getTrayTransportHighlight() == 1);
        addExcelRow(dataList, "14", "是否提供卸货服务", info.getUnloadingService(), highlight.getUnloadingServiceHighlight() == 1);
        addExcelRow(dataList, "15", "卸货服务收费标准（元/吨）", info.getUnloadingCost(), highlight.getUnloadingCostHighlight() == 1);
        addExcelRow(dataList, "16", "是否需要预约", info.getAppointment(), highlight.getAppointmentHighlight() == 1);
        addExcelRow(dataList, "17", "随车单据需求", info.getDocumentNeed(), highlight.getDocumentNeedHighlight() == 1);
        addExcelRow(dataList, "18", "是否盖章签收 确认", info.getStampConfirm(), highlight.getStampConfirmHighlight() == 1);
        addExcelRow(dataList, "19", "是否能更换无批次纸箱", info.getReplaceBox(), highlight.getReplaceBoxHighlight() == 1);
        addExcelRow(dataList, "20", "异常晚到是否可延迟收货", info.getDelayAccept(), highlight.getDelayAcceptHighlight() == 1);
        addExcelRow(dataList, "21", "其他需求", info.getOtherNeeds(), highlight.getOtherNeedsHighlight() == 1);
        return dataList;
    }

    private static List<LogisticsExcel> generateExcelTemplate() {
        List<LogisticsExcel> dataList = new ArrayList<>();
        // 添加客户名称行（固定字段）
        addExcelRow(dataList, "1", "客户名称", "", false);

        // 从attributes表中获取所有属性定义
        List<AttributeDefinition> attributes = AttributeService.getAllAttributes();
        int rowNum = 2; // 从第2行开始（客户名称是第1行）

        // 根据属性定义动态生成Excel模板
        for (AttributeDefinition attr : attributes) {
            // 使用属性的显示名称作为Excel中的项目名称
            addExcelRow(dataList, String.valueOf(rowNum), attr.getDisplayName(),
                    attr.getDefaultValue() != null ? attr.getDefaultValue() : "", false);
            rowNum++;
        }

        return dataList;
    }

    private static void addExcelRow(List<LogisticsExcel> dataList, String no, String item, String content, boolean highlighted) {
        LogisticsExcel data = new LogisticsExcel();
        data.setNo(no);
        data.setItem(item);
        data.setContent(content);
        data.setRemark("");  // 备注默认为空
        dataList.add(data);
    }


    public static void exportCustomersFromEAV(List<Customer> customers) {
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存Excel文件");
            fileChooser.getExtensionFilters().add(
                    new FileChooser.ExtensionFilter("Excel文件", "*.xlsx")
            );
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            // 格式化日期
            String formattedDate = currentDate.format(formatter);
            String fileName = "客户信息_" + formattedDate + ".xlsx";
            fileChooser.setInitialFileName(fileName);

            File file = fileChooser.showSaveDialog(new Stage());

            if (file != null) {
                exportCustomersToExcel(customers, file.getAbsolutePath());
                CommonUtil.showAlert("导出成功", "Excel文件已成功导出！", Alert.AlertType.INFORMATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
            CommonUtil.showAlert("导出失败", "导出Excel文件时发生错误：" + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    private static void exportCustomersToExcel(List<Customer> customers, String filePath) {
        ExcelWriter excelWriter = null;
        try {
            // 设置样式
            WriteCellStyle headStyle = new WriteCellStyle();
            headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headStyle.setBorderBottom(BorderStyle.THIN);
            headStyle.setBorderLeft(BorderStyle.THIN);
            headStyle.setBorderRight(BorderStyle.THIN);
            headStyle.setBorderTop(BorderStyle.THIN);
            WriteFont headFont = new WriteFont();
            headFont.setBold(true);

            WriteCellStyle contentStyle = new WriteCellStyle();
            contentStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            contentStyle.setBorderBottom(BorderStyle.THIN);
            contentStyle.setBorderLeft(BorderStyle.THIN);
            contentStyle.setBorderRight(BorderStyle.THIN);
            contentStyle.setBorderTop(BorderStyle.THIN);

            // 获取所有属性定义，建立属性名称和ID的映射
            List<AttributeDefinition> attributes = AttributeService.getAllAttributes();
            Map<String, Integer> displayNameToIdMap = new HashMap<>();
            Map<Integer, Integer> attributeRowMap = new HashMap<>(); // 属性ID到行号的映射
            
            // 构建映射关系
            int rowNum = 3; // 从第3行开始（前两行是表头）
            for (AttributeDefinition attr : attributes) {
                displayNameToIdMap.put(attr.getDisplayName(), attr.getAttributeId());
                attributeRowMap.put(attr.getAttributeId(), rowNum++);
            }

            // 创建ExcelWriter对象
            excelWriter = EasyExcel.write(filePath, LogisticsExcel.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, contentStyle))
                    .registerWriteHandler(new CellWriteHandler() {
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            Row row = context.getRow();
                            if (row.getRowNum() == 0 && context.getColumnIndex() >= 0 && context.getColumnIndex() <= 3) {
                                row.setHeightInPoints(30);
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                WriteFont headFont = new WriteFont();
                                headFont.setBold(true);
                                headFont.setFontName("宋体");
                                headFont.setFontHeightInPoints((short) 14);
                                writeCellStyle.setWriteFont(headFont);
                            }
                        }
                    }).registerWriteHandler(new CellWriteHandler() {
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            Row row = context.getRow();
                            if (row.getRowNum() == 1 && context.getColumnIndex() >= 0 && context.getColumnIndex() <= 3) {
                                row.setHeightInPoints(25);
                                WriteCellData<?> cellData = context.getFirstCellData();
                                WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                writeCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                                writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                                WriteFont sHeadFont = new WriteFont();
                                sHeadFont.setFontName("宋体");
                                sHeadFont.setFontHeightInPoints((short) 12);
                                writeCellStyle.setWriteFont(sHeadFont);
                            }
                        }
                    })
                    // 添加标红处理的CellWriteHandler
                    .registerWriteHandler(new CellWriteHandler() {
                        @Override
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            // 跳过表头行
                            if (context.getRow().getRowNum() < 3) {
                                return;
                            }

                            // 获取当前Sheet名称
                            String sheetName = context.getWriteSheetHolder().getSheetName();
                            
                            // 从Sheet名称中提取客户ID
                            if (sheetName != null && sheetName.startsWith("客户")) {
                                String[] parts = sheetName.split("_");
                                if (parts.length > 0) {
                                    String customerIdStr = parts[0].substring(2); // 去掉"客户"二字
                                    try {
                                        int customerId = Integer.parseInt(customerIdStr);
                                        
                                        // 在customers列表中查找对应的客户
                                        Customer customer = null;
                                        for (Customer c : customers) {
                                            if (c.getCustomerId() == customerId) {
                                                customer = c;
                                                break;
                                            }
                                        }
                                        
                                        if (customer != null) {
                                            // 获取当前行号
                                            int currentRow = context.getRow().getRowNum();
                                            
                                            // 遍历属性ID到行号的映射
                                            for (Map.Entry<Integer, Integer> entry : attributeRowMap.entrySet()) {
                                                int attributeId = entry.getKey();
                                                int mappedRow = entry.getValue();
                                                
                                                // 如果当前行是需要标红的属性所在的行
                                                if (currentRow == mappedRow && customer.isAttributeHighlighted(attributeId)) {
                                                    // 获取当前单元格的样式
                                                    WriteCellData<?> cellData = context.getFirstCellData();
                                                    WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                                                    
                                                    // 设置字体颜色为红色
                                                    WriteFont font = new WriteFont();
                                                    font.setColor(IndexedColors.RED.getIndex());
                                                    writeCellStyle.setWriteFont(font);
                                                    break;
                                                }
                                            }
                                        }
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    })
                    .relativeHeadRowIndex(0)
                    .build();

            // 对每个客户创建一个工作表
            for (int i = 0; i < customers.size(); i++) {
                Customer customer = customers.get(i);
                String sheetName = "客户" + customer.getCustomerId() + "_" + customer.getCustomerName();
                
                // 生成数据
                List<LogisticsExcel> dataList = generateExcelDataFromCustomer(customer);
                
                // 创建新的写入sheet对象
                WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetName).build();
                
                // 写入数据
                excelWriter.write(dataList, writeSheet);
            }

        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
    
    private static List<LogisticsExcel> generateExcelDataFromCustomer(Customer customer) {
        List<LogisticsExcel> dataList = new ArrayList<>();

        // 获取客户的属性值
        Map<Integer, String> attributeValues = customer.getAttributeValues();
        int rowNum = 1;

        //添加客户名称行
        LogisticsExcel firstData = new LogisticsExcel();
        firstData.setSerialNo(String.valueOf(rowNum));
        firstData.setItem("客户名称");
        firstData.setContent(customer.getCustomerName());
        firstData.setRemark("");  // 备注默认为空
        dataList.add(firstData);
        rowNum++;
        // 只添加客户实际拥有的属性
        for (Map.Entry<Integer, String> entry : attributeValues.entrySet()) {
            int attributeId = entry.getKey();
            String value = entry.getValue();
            
            // 通过attributeId获取属性定义
            AttributeDefinition attr = AttributeService.getAttributeById(attributeId);
            if (attr != null) {
                String displayName = attr.getDisplayName();
                
                LogisticsExcel data = new LogisticsExcel();
                data.setSerialNo(String.valueOf(rowNum));
                data.setItem(displayName);
                data.setContent(value);
                data.setRemark("");  // 备注默认为空
                dataList.add(data);
                rowNum++;
            }
        }
        
        return dataList;
    }

    public static void exportCustomerTemplate() {
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存客户物流信息模板");
            fileChooser.getExtensionFilters().add(
                    new FileChooser.ExtensionFilter("Excel文件", "*.xlsx")
            );
            fileChooser.setInitialFileName("客户物流信息模板.xlsx");

            File file = fileChooser.showSaveDialog(new Stage());
            if (file != null) {
                List<LogisticsExcel> dataList = new ArrayList<>();
                
                // 获取所有属性定义
                List<AttributeDefinition> attributes = AttributeService.getAllAttributes();
                int rowNum = 1;
                
                // 添加客户名称行
                LogisticsExcel firstData = new LogisticsExcel();
                firstData.setSerialNo(String.valueOf(rowNum));
                firstData.setItem("客户名称");
                firstData.setContent("");
                firstData.setRemark("必填");
                dataList.add(firstData);
                rowNum++;
                
                // 添加其他属性行
                for (AttributeDefinition attr : attributes) {
                    LogisticsExcel data = new LogisticsExcel();
                    data.setSerialNo(String.valueOf(rowNum));
                    data.setItem(attr.getDisplayName());
                    data.setContent(attr.getDefaultValue() != null ? attr.getDefaultValue() : "");
                    data.setRemark("");
                    dataList.add(data);
                    rowNum++;
                }

                // 写入Excel
                EasyExcel.write(file, LogisticsExcel.class)
                        .sheet("客户物流信息模板")
                        .doWrite(dataList);

                CommonUtil.showAlert("导出成功", "模板文件已成功导出！", Alert.AlertType.INFORMATION);
            }
        } catch (Exception e) {
            CommonUtil.showAlert("导出失败", "导出模板文件时发生错误：" + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    public static void exportRequirementTemplate() {
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存运输要求模板");
            fileChooser.getExtensionFilters().add(
                    new FileChooser.ExtensionFilter("Excel文件", "*.xlsx")
            );
            fileChooser.setInitialFileName("运输要求模板.xlsx");

            File file = fileChooser.showSaveDialog(new Stage());
            if (file != null) {
                List<LogisticsRequirementExcel> dataList = new ArrayList<>();
                
                // 添加固定的运输要求字段
                String[] items = {"项目", "具体要求", "处理时效", "责任人", "监管人"};
                for (int i = 0; i < items.length; i++) {
                    LogisticsRequirementExcel data = new LogisticsRequirementExcel();
                    data.setSerial_no(String.valueOf(i + 1));
                    data.setItem(items[i]);
                    data.setRequirement("");
                    data.setProEffi("");
                    data.setResponsiblePerson("");
                    data.setSupervisor("");
                    dataList.add(data);
                }

                // 写入Excel
                EasyExcel.write(file, LogisticsRequirementExcel.class)
                        .sheet("运输要求模板")
                        .doWrite(dataList);

                CommonUtil.showAlert("导出成功", "模板文件已成功导出！", Alert.AlertType.INFORMATION);
            }
        } catch (Exception e) {
            CommonUtil.showAlert("导出失败", "导出模板文件时发生错误：" + e.getMessage(), Alert.AlertType.ERROR);
        }
    }
} 